package com.ciwong.epaper.modules.evaluate.ui;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.TrafficStats;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.ciwong.ciwongwrite.utils.CWUtils;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.common.CheckIsExamForDetail;
import com.ciwong.epaper.common.dialogbottom.reread.BaseReReadBottomDialog;
import com.ciwong.epaper.common.dialogbottom.reread.CheckReReadWordBottomDialog;
import com.ciwong.epaper.modules.cordva.CordovaWebViewTestActivity;
import com.ciwong.epaper.modules.dictation.ui.DictationRedoAndResultActivity;
import com.ciwong.epaper.modules.epaper.bean.Answer;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.bean.ModuleInfo;
import com.ciwong.epaper.modules.epaper.bean.WorkAnswers;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.modules.epaper.util.RepeatKeyUtil;
import com.ciwong.epaper.modules.evaluate.bean.AnswerRecorder;
import com.ciwong.epaper.modules.evaluate.bean.RepeatAnswerInfo;
import com.ciwong.epaper.modules.evaluate.bean.SubmitResult;
import com.ciwong.epaper.modules.evaluate.bean.WordDetail;
import com.ciwong.epaper.modules.evaluate.ui.dialogfragment.bean.CheckReReadBean;
import com.ciwong.epaper.modules.evaluate.util.ScoreTipsDialog;
import com.ciwong.epaper.modules.evaluate.util.UnitSpeechControler;
import com.ciwong.epaper.modules.evaluate.util.WordResultScoreController;
import com.ciwong.epaper.modules.me.bean.MyWork;
import com.ciwong.epaper.modules.me.bean.RequirementContent;
import com.ciwong.epaper.modules.me.bean.WorkContents;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.ui.JsonParserUtil;
import com.ciwong.epaper.modules.me.util.AddPointTypes;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.me.util.MeUtil;
import com.ciwong.epaper.modules.share.QQShareHelper;
import com.ciwong.epaper.modules.share.QQShareListener;
import com.ciwong.epaper.modules.share.WxShareHelper;
import com.ciwong.epaper.modules.share.WxShareListener;
import com.ciwong.epaper.modules.share.bean.ShareMsgObj;
import com.ciwong.epaper.service.UploadeFailService;
import com.ciwong.epaper.util.Base64Utils;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.PopWindowUtil;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.widget.NewLoginDialog;
import com.ciwong.epaper.widget.SubmitSuccessfulResultPage;
import com.ciwong.libs.oralevaluate.bean.EvaluateResult;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.FileUtils;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.BuyServiceDialog;
import com.ciwong.mobilelib.widget.CWDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.UiError;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import static com.ciwong.epaper.common.dialogbottom.reread.BaseReReadBottomDialog.mHashMap;
import static com.ciwong.epaper.common.dialogbottom.reread.CheckReReadWordBottomDialog.SCORE_60;
import static com.ciwong.epaper.common.dialogbottom.reread.CheckReReadWordBottomDialog.SCORE_70;
import static com.ciwong.epaper.common.dialogbottom.reread.CheckReReadWordBottomDialog.SCORE_80;
import static com.ciwong.epaper.common.dialogbottom.reread.CheckReReadWordBottomDialog.SCORE_90;

/**
 * 单词重读提交结果页面
 */
public class RereadWordResultActivity extends BaseActivity implements RereadWordResultAdapter.ReReadWordListener, View.OnClickListener, WordResultScoreController.WordResultInterFace {
    private Context mContext = this;
    //为什么传过来的就是ArrayList  后面要仔细分析一下
    private ArrayList<WordDetail> mWordDetailList;
    private ArrayList<AnswerRecorder> mAnswerRecorderList;
    private ArrayList<WorkAnswers<RepeatAnswerInfo>> userAnswersList;
    private ListView mRereadWordResultListView;
    private RereadWordResultAdapter mRereadWordResultAdapter;
    private String mUuid;

    //截止时间
    private long effectiveDate = -1;

    private boolean isSubmited = false, isHasSubmited = false;// 是否提交作业成功  是否已经提交过作业

    public Button commit_homework_btn, retry_submit_bt;//交作业按钮   重新提交按钮
    private LinearLayout submiting;//结果容器  提交中   提交失败
    private RelativeLayout result_contail, submit_fail;
    private ViewGroup submit_result_lay;//提交成功页面
    private SubmitSuccessfulResultPage score_result_page;//结果控件
    //提交作业成功 返回的作业时长
    private long returnWorkLong;

    private SeekBar submit_seek_bar_make_score;//提交进度

    private int prog = 0;//上传完成数量


    /**
     * 提交次数
     */


    protected Answer answer;
    private ImageView wechat, wechatFriend, qq, qqFriend;//分享

    private String versionId, workId, doWorkId, parentVersionId, mTitleText, bookId, chapterId;
    private float acuScore;
    //单词跟读默认一百分
    private float totalScore = 100;
    private int workLong;
    private DownLoadInfo mDownLoadInfo;
    private Module mModule;
    private int position;
    private long nowTime = 0;
    private int showScoreMode;
    private long startTime;
    private WordResultScoreController wordResultScoreController;
    //用来判断是否重评完所有
    private int countIsScoreAll;
    //需要重新评分的答案集合
    List<AnswerRecorder> scoreAgainAnswerList = new ArrayList<>();
    /**
     * 是否是手动模式
     */
    private boolean isShouDongMode;


    protected RequirementContent requirementContent;

    private final int MSG_NET_SPEED = 100;
    private TextView tx_upload_progress;
    private int remainUploadSize;
    protected int readMode;//跟读模式
    //是否是考试模式
    private boolean mIsKaoShiMode = true;

    private WorkContents mWorkContents;
    private int mRequestFrom;
    private ScoreTipsDialog scoreTipsDialog;
    private EApplication application;
    /**
     * 默认服务包剩余使用时间
     */
    private boolean serviceExpired;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case MSG_NET_SPEED:
                    try {
                        int speed = (int) msg.obj;
                        remainUploadSize = remainUploadSize - speed;
                        if (remainUploadSize < 0) {
                            remainUploadSize = 0;
                        }
                        int remainSecods = 0;
                        if (speed > 0) {
                            remainSecods = remainUploadSize / speed;
                        } else {
                            //如果网速为0 当做1kb
                            remainSecods = remainUploadSize;
                        }
                        tx_upload_progress.setVisibility(View.VISIBLE);
                        tx_upload_progress.setText(ListenSpeakUtil.formatNetSpeed(RereadWordResultActivity.this, speed, remainSecods, true));
                    } catch (Exception e) {
                        e.getStackTrace();
                    }
                    break;

            }
        }
    };


    @Override
    protected void preCreate() {
        super.preCreate();

        mWorkContents = (WorkContents) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_WORK_CONTENTS);
        mRequestFrom = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_REQUEST_CODE_FROM, -1);
        requirementContent = (RequirementContent) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_REQU_CONTENT);
        scoreTipsDialog = new ScoreTipsDialog(this);
        scoreTipsDialog.setCanceledOnTouchOutside(false);//点击屏幕 dialog不消失
        scoreTipsDialog.setCancelable(false);//点击屏幕或返回按钮 dialog不消失

    }

    //单词重读逻辑(单个单词)
    @Override
    public void reReadWord(int position) {
        EpaperJumpManager.jumpToWordReadRepeat(R.string.go_back, RereadWordResultActivity.this, mWordDetailList.get(position), mDownLoadInfo, true, readMode, mUuid, RequestCode.RereadWordResultActivityResquestCode.REPEATE_WORD_REQUEST, mTitleText, isShouDongMode);
    }

    //单词重读逻辑(多个单词)
    public void reReadWordList(boolean isGreater, int flag) {
        List<WordDetail> list = filterScoreInterval(isGreater, flag);
        EpaperJumpManager.jumpToWordReadRepeat(R.string.go_back, RereadWordResultActivity.this, list, mDownLoadInfo, true, readMode, mUuid, RequestCode.RereadWordResultActivityResquestCode.REPEATE_WORD_REQUEST, mTitleText);
    }

    /**
     * 筛选固定分数段的单词详情集合
     *
     * @param isGreater true 是大于 false 者小于（相对于flag）
     * @param flag      做为分数段标记 如flag=90则是90分
     * @return
     */
    private List<WordDetail> filterScoreInterval(boolean isGreater, int flag) {
        List<WordDetail> listFilter = new ArrayList<>();
        if (mAnswerRecorderList == null || mAnswerRecorderList.size() <= 0) return listFilter;
        for (int i = 0; i < mAnswerRecorderList.size(); i++) {
            AnswerRecorder answerRecorder = mAnswerRecorderList.get(i);
            if (isGreater) {
                if (answerRecorder.getScore() > flag) {
                    listFilter.add(mWordDetailList.get(i));
                }
            } else {
                if (answerRecorder.getScore() < flag) {
                    listFilter.add(mWordDetailList.get(i));
                }
            }
        }
        return listFilter;
    }


    public void isSupportQQAndQQZone() {
        if (EConstants.QQ_APP_ID.equals("") || null == EConstants.QQ_APP_ID) {
            qq.setImageResource(R.mipmap.share_qq_unstalled);
            qqFriend.setImageResource(R.mipmap.share_qq_space_unstalled);
            qq.setEnabled(false);
            qqFriend.setEnabled(false);
        }
    }


    @Override
    protected int setView() {
        return R.layout.activity_reread_word_result;
    }

    @Override
    protected void findViews() {
        mRereadWordResultListView = (ListView) findViewById(R.id.reread_word_result_lv);
        commit_homework_btn = (Button) findViewById(R.id.commit_homework_btn);
        retry_submit_bt = (Button) findViewById(R.id.retry_submit_bt);
        result_contail = (RelativeLayout) findViewById(R.id.result_contail);
        submiting = (LinearLayout) findViewById(R.id.submiting);
        submit_fail = (RelativeLayout) findViewById(R.id.submit_fail);
        submit_seek_bar_make_score = (SeekBar) findViewById(R.id.submit_seek_bar_make_score);
        submit_result_lay = (ViewGroup) findViewById(R.id.submit_result_lay);
        score_result_page = findViewById(R.id.score_result_page);

        wechat = (ImageView) score_result_page.findViewById(R.id.share_weixin);
        wechatFriend = (ImageView) score_result_page.findViewById(R.id.share_weixin_friend);
        qq = (ImageView) score_result_page.findViewById(R.id.share_qq);
        qqFriend = (ImageView) score_result_page.findViewById(R.id.share_qq_space);
        tx_upload_progress = (TextView) findViewById(R.id.tx_upload_progress);

        btn_return_last_page = (Button) score_result_page.findViewById(R.id.btn_return_last_page);
        iv_close_page = (ImageView) score_result_page.findViewById(R.id.iv_close_page);
    }

    private Button btn_return_last_page;
    private ImageView iv_close_page;
    private int hasScoreCount;
    private int allScoreCount;

    @Override
    protected void initEvent() {
        btn_return_last_page.setOnClickListener(this);
        iv_close_page.setOnClickListener(this);
        commit_homework_btn.setOnClickListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {//提交作业
                UploadeFailService.startService();
                try {
                    if (EConstants.IS_YOUKE) {
                        EConstants.WORD_IS_YOUKE_LOGIN = true;
                        NewLoginDialog newLoginDialog = new NewLoginDialog(RereadWordResultActivity.this);
                        newLoginDialog.showLoginDialog();
                    } else {
                        if (NetworkUtils.isOnline()) {
                            if (null != scoreAgainAnswerList) {
                                //清除list避免重复提交叠加
                                scoreAgainAnswerList.clear();
                            }
                            for (int i = 0; i < mAnswerRecorderList.size(); i++) {
                                if (mAnswerRecorderList.get(i).getScore() == -1) {
                                    scoreAgainAnswerList.add(mAnswerRecorderList.get(i));
                                }
                            }
                            if (scoreAgainAnswerList.size() > 0) {
                                allScoreCount = scoreAgainAnswerList.size();
                                hasScoreCount = 0;
                                countIsScoreAll = 0;
                                showTips();
                                scoreRetry();
                            } else {
                                acuScore = getAvgScore();
                                submit();
                            }


                        } else {
                            ToastUtil.INSTANCE.toastCenterNoNetError();
                        }
                    }

                } catch (Exception e) {
                    e.getStackTrace();
                }
//                checkReReadWords();
            }
        });

        retry_submit_bt.setOnClickListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {//重新提交
                try {
                    if (EConstants.IS_YOUKE) {
                        EConstants.WORD_IS_YOUKE_LOGIN = true;
                        NewLoginDialog newLoginDialog = new NewLoginDialog(RereadWordResultActivity.this);
                        newLoginDialog.showLoginDialog();
                    } else {
                        if (NetworkUtils.isOnline()) {
                            submit_fail.setVisibility(View.GONE);
                            acuScore = getAvgScore();
                            submit();
                        } else {
                            ToastUtil.INSTANCE.toastCenterNoNetError();
                        }
                    }
                } catch (Exception e) {
                    e.getStackTrace();
                }
            }
        });

        score_result_page.setOnCheckDetailListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean orNotWatchDetails = CheckIsExamForDetail.INSTANCE.isOrNotWatchDetails(RereadWordResultActivity.this, answer.getContentId() + "", 0);
                if (!orNotWatchDetails)
                    return;
                if (serviceExpired) {
                    // 直接跳转到新的学习记录页面
                    jumpToStudyRecordH5();
                } else {
                    setBuyServiceDialog();
                }
            }
        });
        score_result_page.setOnCheckTipsListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean orNotWatchDetails = CheckIsExamForDetail.INSTANCE.isOrNotWatchDetails(RereadWordResultActivity.this, answer.getContentId() + "", 0);
                if (!orNotWatchDetails)
                    return;
                if (serviceExpired) {
                    // 直接跳转到新的学习记录页面
                    jumpToStudyRecordH5();
                } else {
                    setBuyServiceDialog();
                }
            }
        });

        wechat.setOnClickListener(new ViewOnClickListener() {//微信分享
            @Override
            public void avertRepeatOnClick(View v) {
                weChatShare(1);
            }
        });
        wechatFriend.setOnClickListener(new ViewOnClickListener() {//
            @Override
            public void avertRepeatOnClick(View v) {
                weChatShare(2);
            }

        });

        qq.setOnClickListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {
                qqShare("QQ");
            }
        });

        qqFriend.setOnClickListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {
                qqShare("QZone");
            }
        });

        setGoBackListener(goBackListener);
    }

    /**
     * 直接跳转到新的学习记录页面
     */
    private void jumpToStudyRecordH5() {
        try {
            saveDoWorkRecord(null, null);
            String saveUuid = RepeatKeyUtil.getWordUuidSaveKey(mDownLoadInfo, mModule, position, workId, readMode);
            FileUtils.delete(ESystem.getAnswersUuidPath(saveUuid));
            CWSys.setSharedInt(getSaveTime(), 0);
            //直接跳转到新的学习记录页面
            String url = EpaperConstant.URL_READING_REPEAD + "pageType=1";
            StringBuffer sb = new StringBuffer(url);
            sb.append("&clientId=");
            sb.append(EConstants.CLIENT_ID);
            long useeId = getUserInfoBase().getUserId();
            sb.append("&userId=");
            sb.append(useeId);
            sb.append("&brandId=");
            sb.append(EApplication.BRAND_ID);
            sb.append("&versionId=");
            sb.append(versionId);
            sb.append("&parentVersionId=");
            sb.append(parentVersionId);
            sb.append("&doWorkId=");
            sb.append(doWorkId);
            String title;
            try {
                title = java.net.URLEncoder.encode(mTitleText, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                title = "";
            }
            title = title.replace("+", "%20");
            sb.append("&title=");
            sb.append(title);
            MeJumpManager.jumpToStudyRecordH5Activity(ModuleInfo.ModuleInfoId.MODULE_ID_REPEAT, RereadWordResultActivity.this, R.string.go_back, -1, sb.toString(), mTitleText, 0);

        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    private BuyServiceDialog buyServiceDialog;

    public void setBuyServiceDialog() {
        if (buyServiceDialog == null) {
            buyServiceDialog = new BuyServiceDialog(RereadWordResultActivity.this);
            buyServiceDialog.setMenuOnClickListeners(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    if (answer != null && answer.getWorkType() > 0) {
                        int serviceId = 0;
                        try {
                            serviceId = answer.getWorkType();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        //购买服务包
                        MeJumpManager.jumpBuyService(RereadWordResultActivity.this, R.string.go_back, serviceId, -1, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_PAY, "");
                    } else {
                        //拓展服务
                        MeJumpManager.jumpToResourseCenterH5Activity(RereadWordResultActivity.this, R.string.go_back, getResources().getString(R.string.resource_center));
                    }
                    buyServiceDialog.dismiss();
                }
            });
            buyServiceDialog.setClosOnClickListeners(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    buyServiceDialog.dismiss();
                }
            });
        }
        buyServiceDialog.show();
    }

    private void checkReReadWords() {

//        CheckReReadDialogFragment checkReReadDialogFragment = new CheckReReadDialogFragment();
//        checkReReadDialogFragment.show(getSupportFragmentManager(), " ");
        CheckReReadWordBottomDialog checkReReadWordBottomDialog = new CheckReReadWordBottomDialog(this, R.style.DialogStyleGuide);
        checkReReadWordBottomDialog.setCanceledOnTouchOutside(true);
        checkReReadWordBottomDialog.setOnItemCallBackListener(new BaseReReadBottomDialog.ItemCallBack() {
            @Override
            public void onItemCallBack(CheckReReadBean bean, int position) {
                ToastUtil.INSTANCE.toastCenter(getBaseContext(), "位置：" + position);
                reReadWordList(bean.isGreater(), bean.getFlag());
            }
        });
        checkReReadWordBottomDialog.setData(filterViewData());
        checkReReadWordBottomDialog.setDialogTitle(getResources().getString(R.string.dialog_check_word_range));
        checkReReadWordBottomDialog.show();

    }

    /**
     * 筛选可以看到的分数段ui
     */
    private List<CheckReReadBean> filterViewData() {
        List<CheckReReadBean> listCheckReReadBean = new ArrayList<>();
        int flag = 100;//标记最大分值端点
        for (AnswerRecorder answerRecorder : mAnswerRecorderList) {
            int score = answerRecorder.getScore();
            if (score <= flag) {
                flag = score;
            }
        }
        CheckReReadBean checkReReadBean90 = mHashMap.get(SCORE_90);
        CheckReReadBean checkReReadBean80 = mHashMap.get(SCORE_80);
        CheckReReadBean checkReReadBean70 = mHashMap.get(SCORE_70);
        CheckReReadBean checkReReadBean60 = mHashMap.get(SCORE_60);
        if (flag > checkReReadBean60.getFlag()) {
            checkReReadBean60.setClickable(false);
            if (flag > checkReReadBean70.getFlag()) {
                checkReReadBean70.setClickable(false);
                if (flag > checkReReadBean80.getFlag()) {
                    checkReReadBean80.setClickable(false);
                    if (flag > checkReReadBean90.getFlag()) {
                        checkReReadBean90.setClickable(false);
                    }
                }
            }
        }
        listCheckReReadBean.add(checkReReadBean90);
        listCheckReReadBean.add(checkReReadBean80);
        listCheckReReadBean.add(checkReReadBean70);
        listCheckReReadBean.add(checkReReadBean60);
        return listCheckReReadBean;
    }


    /**
     * "QQ"代表分享给QQ好友，"QZone"代表分享到QQ空间
     *
     * @param qq
     */

    private void qqShare(String qq) {
        try {
            ShareMsgObj shareMsgObj = new ShareMsgObj();
            shareMsgObj.setShareType(ShareMsgObj.ShareType.SHARE_WEB);
            shareMsgObj.setLocalImgUrl(FileUtil.getShareWordIconLocalPath(getApplicationContext()));
            shareMsgObj.setUrl(getShareBase64Url());
            String score = getString(R.string.speech_word_score, MeUtil.formatScore(acuScore));
            String shareContent = getString(R.string.str_share_contentword, score);
            if (qq.equals("QQ")) {
                shareMsgObj.setMsgDesription(shareContent);
                shareMsgObj.setMsgTitle(mTitleText);
                QQShareHelper.getInstance().shareToQQ(RereadWordResultActivity.this, shareMsgObj, new QQShareListener() {
                    @Override
                    public void onQQShareSucc(Object var) {
                        shareAddPointType(doWorkId, AddPointTypes.SHERE_SCORE);
                    }

                    @Override
                    public void onQQShareFailure(UiError var1) {
                    }

                    @Override
                    public boolean onQQShareCancel() {
                        return false;
                    }
                });
            } else if (qq.equals("QZone")) {
                shareMsgObj.setMsgTitle(shareContent);
                shareMsgObj.setImg_url(FileUtil.getShareWordIconLocalPath(getApplicationContext()));
                QQShareHelper.getInstance().shareToQZone(RereadWordResultActivity.this, shareMsgObj, new QQShareListener() {
                    @Override
                    public void onQQShareSucc(Object var) {
                        shareAddPointType(doWorkId, AddPointTypes.SHERE_SCORE);
                    }

                    @Override
                    public void onQQShareFailure(UiError var1) {

                    }

                    @Override
                    public boolean onQQShareCancel() {

                        return false;
                    }
                });
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    /**
     * 1代表分享给好友，2代表分享到朋友圈
     *
     * @param wxType
     */
    private void weChatShare(int wxType) {
        try {
            WxShareHelper.getInstance().initWxShare(RereadWordResultActivity.this, new WxShareListener() {
                @Override
                public void onWxShareing(String str) {

                    Log.d("sharetest", "##########onWxShareing######" + str);
                }

                @Override
                public void onWxShareSucc(String var) {
                    shareAddPointType(doWorkId, AddPointTypes.SHERE_SCORE);
                    Log.d("sharetest", "##########onWxShareSucc######" + var);
                }

                @Override
                public void onWxShareFailure(int var, String var1) {
                    Log.d("sharetest", "##########onWxShareFailure######" + var1);
                }

                @Override
                public boolean onWxShareCancel() {
                    Log.d("sharetest", "##########onWxShareCancel######");
                    return false;
                }
            });
            ShareMsgObj shareMsgObj = new ShareMsgObj();
            shareMsgObj.setWxType(wxType);
            shareMsgObj.setShareType(ShareMsgObj.ShareType.SHARE_WEB);
            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.word_share_icon);
            shareMsgObj.setThunbBmp(bmp);

            shareMsgObj.setUrl(getShareBase64Url());
            String score = getString(R.string.speech_word_score, MeUtil.formatScore(acuScore));
            String shareContent = getString(R.string.str_share_contentword, score);
            if (wxType == 1) {
                shareMsgObj.setMsgDesription(shareContent);
                shareMsgObj.setMsgTitle(mTitleText);
            } else if (wxType == 2) {
                shareMsgObj.setMsgTitle(shareContent);
            }
            WxShareHelper.getInstance().sendReq(shareMsgObj);
        } catch (Exception e) {
            e.getStackTrace();
        }

    }

    @Override
    public void scoreError() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtil.INSTANCE.toastCenterError(R.string.submit_fail);
            }
        });

    }

    private void shareAddPointType(String doWorkId, String type) {
        MeDao.getInstance().addPoint(EApplication.getInstance().getUserInfoBase().getUserId() + "", EApplication.getInstance().getUserInfoBase().getRealName(), type, doWorkId);
    }

    @Override
    public void onBackPressed() {
        goBackListener.goBack();
    }

    //得到加密后的URL
    public String getShareBase64Url() {
        String shareUrl;
        StringBuffer sb1 = new StringBuffer(EpaperConstant.URL_READING_REPEAD);
        StringBuffer sb = new StringBuffer();
        sb.append("pageType=2");
        sb.append("&clientId=");
        sb.append(EConstants.CLIENT_ID);
        long useeId = getUserInfoBase().getUserId();
        sb.append("&userId=");
        sb.append(useeId);
        sb.append("&brandId=");
        sb.append(EApplication.BRAND_ID);
        sb.append("&versionId=");
        sb.append(versionId);
        sb.append("&parentVersionId=");
        sb.append(parentVersionId);
        sb.append("&doWorkId=");
        sb.append(doWorkId);
        String param = Base64Utils.getBase64(sb.toString());
        shareUrl = sb1.append(param).toString();
        return shareUrl;
    }


    @Override
    protected void onResume() {
        super.onResume();
        WxShareHelper.getInstance().onResumeResultData();
    }

    @Override
    protected void init() {
        //上传监听
        TAG = "retryscore2";
        application = (EApplication) getApplication();
        if (application != null) {
            serviceExpired = application.isServiceExpired();
        }
        if (!serviceExpired) {
            if (mWorkContents != null && mWorkContents.getIsFree() == 1) {
                serviceExpired = true;
            }
        }
        isSupportQQAndQQZone();
        setValideSource(false);
        setBackImg(R.mipmap.icon_x_exit);

//        if (netSpeedTask.cancel())
        {
            new Timer().schedule(netSpeedTask, 1000, 1000); // 1s后启动任务，每2s执行一次
        }
        if (!serviceExpired) {
            String text = "查看分数";
            SpannableString spannableString = new SpannableString(text);
            // 定义颜色（例如红色）
            int color = getResources().getColor(R.color.color_light_green);
            // 创建 ForegroundColorSpan 对象
            ForegroundColorSpan colorSpan = new ForegroundColorSpan(color);
            spannableString.setSpan(colorSpan, 0, text.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannableString.setSpan(new UnderlineSpan(), 0, text.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
            setRightSpannaText(spannableString);
            setRightBtnEnable(true);
            setRightBtnListener(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    setBuyServiceDialog();
                }
            });
        }
    }

    @Override
    protected void loadData() {
        initData();
        mRereadWordResultListView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int hasShowCount = CWSys.getSharedInt(EConstants.SHARE_KEY_REPEAT_TIPS + EApplication.getInstance().getUserInfoBase().getUserId(), 0);
                if (!(hasShowCount >= 3)) {
                    View v = mRereadWordResultListView.getChildAt(0);
                    if (v != null) {
                        View score_tv = v.findViewById(R.id.score_tv);
                        View word_result_lay = v.findViewById(R.id.word_result_lay);
                        if (!mIsKaoShiMode) {
                            //只有手动模式显示跟读提示
                            PopWindowUtil.showTipPopupWindow2(score_tv, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                }
                            });
                        }
                        hasShowCount++;
                        CWSys.setSharedInt(EConstants.SHARE_KEY_REPEAT_TIPS + EApplication.getInstance().getUserInfoBase().getUserId(), hasShowCount);
                    }
                }
                mRereadWordResultListView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });


    }


    private void showDailog() {
        CWDialog mDialog = new CWDialog(this);
        // mDialog.setTitle(R.string.lear_title);
        mDialog.setMessage(R.string.confirm_back_work);
        mDialog.setPositiveButton(android.R.string.cancel, null);
        mDialog.setNegativeButton(R.string.ok,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.dismiss();
                        finish();

                    }
                });
        mDialog.show();
    }

    private void initData() {
        Intent intent = getIntent();
        if (intent == null) {
            return;
        }

        Bundle mBundle = new Bundle();
        mBundle = intent.getBundleExtra(IntentFlag.INTENT_FLAG_OBJ);
        try {
            mAnswerRecorderList = (ArrayList<AnswerRecorder>) mBundle.getSerializable(IntentFlag.INTENT_FLAG_USERANSWERROCORD);
            userAnswersList = (ArrayList<WorkAnswers<RepeatAnswerInfo>>) mBundle.getSerializable(IntentFlag.INTENT_FLAG_USERANSWERLIST);
            mWordDetailList = (ArrayList<WordDetail>) mBundle.getSerializable(IntentFlag.INTENT_FLAG_WORDSLIST);
            answer = (Answer) mBundle.getSerializable(IntentFlag.INTENT_FLAG_ANSWER);
            mDownLoadInfo = (DownLoadInfo) mBundle.getSerializable(IntentFlag.INTENT_FLAG_DOWNLOAD_INFO);
            mModule = (Module) mBundle.getSerializable(IntentFlag.INTENT_FLAG_MODULE);
            position = intent.getIntExtra(IntentFlag.INTENT_FLAG_POSITION, 0);
            effectiveDate = getIntent().getLongExtra(IntentFlag.INTENT_FLAG_WORK_EFFECTIV_TIME, -1);
            versionId = answer.getVersionId();
            workId = answer.getWorkId();


            parentVersionId = answer.getParentVersionId();
            mTitleText = answer.getResourceName();
            workLong = answer.getWorkLong();
            bookId = answer.getPackageId();
            setTitleText(mTitleText);

            mUuid = intent.getStringExtra(IntentFlag.INTENT_FLAG_UUID);

            readMode = intent.getIntExtra(IntentFlag.INTENT_FLAG_READMODLE, 0);
            mIsKaoShiMode = intent.getBooleanExtra(IntentFlag.INTENT_FLAG_IS_KAOSHI_MODE, false);
            isShouDongMode = intent.getBooleanExtra(IntentFlag.INTENT_FLAG_IS_SHOUDONG_MODE, false);

            if (CWSys.getSharedBoolean(getSubmitStateKey(), false)) {//已经提交过 直接显示提交失败页面
                result_contail.setVisibility(View.GONE);
                submiting.setVisibility(View.GONE);
                submit_fail.setVisibility(View.VISIBLE);
            } else {
                mRereadWordResultAdapter = new RereadWordResultAdapter(this, mWordDetailList, mAnswerRecorderList, userAnswersList, mIsKaoShiMode, serviceExpired);
                mRereadWordResultListView.setAdapter(mRereadWordResultAdapter);
                mRereadWordResultAdapter.setReReadWordListener(this);
            }

            acuScore = getAvgScore();
            startTime = CWSys.getSharedLong(ListenSpeakUtil.getAnswerStartTimeKey(mDownLoadInfo, mModule, position, workId), 0);
            if (startTime == 0) {
                startTime = mDownLoadInfo.getStartTime();
            }
            wordResultScoreController = new WordResultScoreController(RereadWordResultActivity.this, mUuid);
            wordResultScoreController.setWordResultInterFace(this);


        } catch (Exception e) {
            e.getStackTrace();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            if (requestCode == Constants.REQUEST_QQ_SHARE || requestCode == Constants.REQUEST_QZONE_SHARE) {
                QQShareHelper.getInstance().onActivityResultData(requestCode, resultCode, data);
            } else if (requestCode == RequestCode.RereadWordResultActivityResquestCode.REPEATE_WORD_REQUEST) {
                if (data == null) {
                    return;
                }
                String yzsAudioUrl = data.getStringExtra(IntentFlag.INTENT_FLAG_STR);
                AnswerRecorder answerRecorder = (AnswerRecorder) data.getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
                EvaluateResult evaluateResult = (EvaluateResult) data.getSerializableExtra(IntentFlag.INTENT_FLAG_EVALUATE_RESULT);
                Iterator<AnswerRecorder> iterator = mAnswerRecorderList.iterator();
                while (iterator.hasNext()) {
                    AnswerRecorder ar = iterator.next();
                    if (ar.getwId().equals(answerRecorder.getwId())) {
                        ar.setGradeWord(answerRecorder.getGradeWord());
                        ar.setScore(answerRecorder.getScore());
                        if (!TextUtils.isEmpty(answerRecorder.getSoundUrl())) {
                            ar.setSoundUrl(answerRecorder.getSoundUrl());
                        }
                        ar.setUsetime(answerRecorder.getUsetime());
                        ar.setAliyunSoundUrl(answerRecorder.getAliyunSoundUrl());
                        ar.setFluency(answerRecorder.getFluency());
                        ar.setIntegrity(answerRecorder.getIntegrity());
                        ar.setPronunciation(answerRecorder.getPronunciation());
                        ar.setSoundUrl(answerRecorder.getSoundUrl());
                    }
                }
                //添加答案
                String versionId = answerRecorder.getwId();
                WorkAnswers tempWorkAnswers = new WorkAnswers();
                tempWorkAnswers.setVersionId(versionId);
                int answerIndex = userAnswersList.indexOf(tempWorkAnswers);
                if (answerIndex != -1) // 该对象已经存在
                {
                    WorkAnswers<RepeatAnswerInfo> wa = userAnswersList
                            .get(answerIndex);
                    wa.setScore(answerRecorder.getScore());
                    if (wa.getAnswers() != null && wa.getAnswers().size() > 0) {
                        if (!TextUtils.isEmpty(answerRecorder.getSoundUrl())) {
                            if (EApplication.isSymbolColoration) {
                                String evaluateResultString = JsonParserUtil.toJson(evaluateResult);
                                if (!TextUtils.isEmpty(evaluateResultString)) {
                                    wa.getAnswers().get(0).setLines(evaluateResultString);
                                    wa.getAnswers().get(0).setYzsAudioUrl(yzsAudioUrl);
                                    wa.getAnswers().get(0).setFluency(answerRecorder.getFluency());
                                    wa.getAnswers().get(0).setIntegrity(answerRecorder.getIntegrity());
                                    wa.getAnswers().get(0).setPronunciation(answerRecorder.getPronunciation());
                                    wa.getAnswers().get(0).setAudioUrl(answerRecorder.getAliyunSoundUrl());
                                }
                            }
                        }
                    }
                }

                //刷新listView
                mRereadWordResultAdapter.notifyDataSetInvalidated();
                mRereadWordResultListView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        int hasShowCount = CWSys.getSharedInt(EConstants.SHARE_KEY_REPEAT_TIPS + EApplication.getInstance().getUserInfoBase().getUserId(), 0);
                        if (!(hasShowCount >= 3)) {
                            View v = mRereadWordResultListView.getChildAt(0);
                            if (v != null) {
                                View score_tv = v.findViewById(R.id.score_tv);
                                if (!mIsKaoShiMode) {
                                    //只有手动模式显示跟读提示
                                    PopWindowUtil.showTipPopupWindow(score_tv, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {

                                        }
                                    });
                                }
                                hasShowCount++;
                                CWSys.setSharedInt(EConstants.SHARE_KEY_REPEAT_TIPS + EApplication.getInstance().getUserInfoBase().getUserId(), hasShowCount);
                            }
                        }
                        mRereadWordResultListView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    }
                });
                //保存记录到本地
                saveDoWorkRecord(userAnswersList, mAnswerRecorderList);
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    public void addScoreCount() {
        hideCricleProgress();
        countIsScoreAll++;
    }

    /**
     * 设置重新评分结果
     */
    @Override
    public void setRestartScoreResult(AnswerRecorder answerRecorder, EvaluateResult evaluateResult, String yzsAudioUrl, boolean isLastOne, boolean isubmitAll) {
        try {
            if (allScoreCount != 0) {
                hasScoreCount++;
                if (countIsScoreAll == allScoreCount) {
                    if (null != scoreTipsDialog) {
                        scoreTipsDialog.dismiss();
                    }
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showTips();
                        }
                    });
                }
            }
            Iterator<AnswerRecorder> iterator = mAnswerRecorderList.iterator();
            while (iterator.hasNext()) {
                AnswerRecorder ar = iterator.next();
                if (ar.getwId().equals(answerRecorder.getwId())) {
                    ar.setScore((int) evaluateResult.getScore());
                    break;
                }
            }
            //添加答案
            String versionId = answerRecorder.getwId();
            WorkAnswers tempWorkAnswers = new WorkAnswers();
            tempWorkAnswers.setVersionId(versionId);
            int answerIndex = userAnswersList.indexOf(tempWorkAnswers);
            if (answerIndex != -1) // 该对象已经存在
            {
                WorkAnswers<RepeatAnswerInfo> wa = userAnswersList
                        .get(answerIndex);
                wa.setScore(answerRecorder.getScore());
                if (wa.getAnswers() != null && wa.getAnswers().size() > 0) {
                    if (!TextUtils.isEmpty(answerRecorder.getSoundUrl())) {
                        if (EApplication.isSymbolColoration) {
                            String evaluateResultString = JsonParserUtil.toJson(evaluateResult);
                            wa.getAnswers().get(0).setYzsAudioUrl(yzsAudioUrl);
                            if (!TextUtils.isEmpty(evaluateResultString)) {
                                wa.getAnswers().get(0).setLines(evaluateResultString);
                            }
                        }
                    }
                }

            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mRereadWordResultAdapter.notifyDataSetChanged();
                }
            });
            //刷新listView
            if (allScoreCount == 0 || countIsScoreAll == allScoreCount) {
                hasScoreCount = 0;
                countIsScoreAll = 0;
                allScoreCount = 0;
                //refresh();
            }


            if (hasScoreCount == allScoreCount && isubmitAll) {
                hasScoreCount = 0;
                countIsScoreAll = 0;
                allScoreCount = 0;
                submit();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 刷新页面
     */
    public void refresh() {
        //刷新listView
        hasScoreCount = 0;
        countIsScoreAll = 0;
        allScoreCount = 0;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (null != scoreTipsDialog && scoreTipsDialog.isShowing()) {
                    scoreTipsDialog.dismiss();
                }
                ToastUtil.INSTANCE.toastCenterError("提交失败，请重新提交");
                mRereadWordResultAdapter.notifyDataSetChanged();
            }
        });

    }

    /**
     * 刷新listview
     */
    @Override
    public void notifydata() {
        //刷新listView
        hasScoreCount = 0;
        countIsScoreAll = 0;
        allScoreCount = 0;
        if (null != scoreAgainAnswerList) {
            scoreAgainAnswerList.clear();
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (null != scoreTipsDialog && scoreTipsDialog.isShowing()) {
                    scoreTipsDialog.dismiss();
                }
                ToastUtil.INSTANCE.toastCenterError("提交失败，请重新提交");
                mRereadWordResultAdapter.notifyDataSetChanged();
            }
        });
        saveDoWorkRecord(userAnswersList, mAnswerRecorderList);

    }


    /**
     * 点击提交按钮重新评分
     */
    public void scoreRetry() {
        AnswerRecorder answerRecorder = new AnswerRecorder();
        boolean isLastOne = false;
        boolean isSubmitAll = true;
        for (int i = 0; i < scoreAgainAnswerList.size(); i++) {
            if (scoreAgainAnswerList.size() == 1) {
                isLastOne = true;
                answerRecorder = scoreAgainAnswerList.get(i);
            } else {
                isLastOne = false;
                answerRecorder = scoreAgainAnswerList.get(i);
                scoreAgainAnswerList.remove(i);
                break;
            }
        }

        WordDetail wordDetail = new WordDetail();
        for (int i = 0; i < mWordDetailList.size(); i++) {
            if (answerRecorder.getwId().equals(mWordDetailList.get(i).getwId())) {
                wordDetail = mWordDetailList.get(i);
                break;
            }
        }
        wordResultScoreController.startScore(answerRecorder, wordDetail, isLastOne, isSubmitAll);
    }


    /**
     * 重新评分
     */
    public void scoreAgain(AnswerRecorder answerRecorder, boolean isLastOne, boolean isSubmitAll) {
        showCricleProgress("正在打分。。。");
        WordDetail wordDetail = new WordDetail();
        for (int i = 0; i < mWordDetailList.size(); i++) {
            if (answerRecorder.getwId().equals(mWordDetailList.get(i).getwId())) {
                wordDetail = mWordDetailList.get(i);
                break;
            }
        }
        wordResultScoreController.startScore(answerRecorder, wordDetail, isLastOne, isSubmitAll);
    }


    public void submit() {//提交作业

        prog = 0;
        isHasSubmited = true;
        saveSubmitState(true);//提交过作业
        remainUploadSize = (int) getRemainUploadFileSize();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                result_contail.setVisibility(View.GONE);
                submiting.setVisibility(View.VISIBLE);
            }
        });

        submitJson();
    }

    /**
     * 重新评分提示
     */
    public void showTips() {
        if (scoreTipsDialog.isShowing()) {
            scoreTipsDialog.setScoreCount(hasScoreCount, allScoreCount);
        } else {
            scoreTipsDialog.show();
            scoreTipsDialog.setScoreCount(hasScoreCount, allScoreCount);
        }
    }


    public void submitJson() {//提交答案数据
        try {
            if (answer == null) {
                return;
            }
            if (submit_fail.getVisibility() == View.VISIBLE) {//如果失败页面显示  则不提交答案
                return;
            }
            answer.setStartTime(startTime);
            answer.setActualScore(getAvgScore());//实际得分
            UserInfoBase userInfoBase = getUserInfoBase();
            if (userInfoBase != null) {
                answer.setUserName(userInfoBase.getRealName());
                answer.setUserId(userInfoBase.getUserId());
            }

            String uuid = CWSys.getSharedString(RepeatKeyUtil.getWordUuidSaveKey(mDownLoadInfo, mModule, position, workId, readMode), null);
            Log.d(TAG, "#######submit() 提交作业 uuid#########" + uuid);
            if (null != uuid) {
                answer.setSessionId(uuid);
                //有可能提交成功清除uuid后再结果页面停留或者用清理软件销毁当前页面，重新生成页面后 uuid 没有
            } else {
                //清除做作业记录  相关缓存
                CWSys.setSharedInt(getSaveTime(), 0);
                saveDoWorkRecord(null, null);
                finish();
                return;
            }

            try {//版本升级  添加没有添加音频地址 添加地址
               /* for (WorkAnswers<RepeatAnswerInfo> workAnswers:userAnswersList){
                    if(workAnswers.getAnswers().get(0)!=null){
                        StringBuffer sb=new StringBuffer(Path);
                        sb.append("work/followread/" + CWSys
                                .getSharedLong(BaseConstants.SHARE_PRE_CURR_LOGIN_USER, 0) + "/");
                        sb.append(uuid+StringUtils.md5(workAnswers.getAnswers().get(0).getWord()));
                        sb.append(EConstants.AUDIO_DEFAULT_SUFFIX);

                        workAnswers.getAnswers().get(0).setAudioUrl(sb.toString());
                    }
                }*/
            } catch (Exception e) {
                e.getStackTrace();
            }


            // 生成userAnswer.json
            Gson gson = new Gson();
            String userAnswerJson = gson.toJson(userAnswersList, new TypeToken<List<WorkAnswers<RepeatAnswerInfo>>>() {
            }.getType());

            if (!TextUtils.isEmpty(userAnswerJson)) {
                answer.setWorkAnswers(userAnswerJson);
            } else {
                //用户答案为空
            }

            if (null != mWorkContents) {
                //如果是作业使用作业接口里面数据的不使用资源里面的
                answer.setVersionId(mWorkContents.getVersionId());
                answer.setParentVersionId(mWorkContents.getParentVersionId());
            }

            String json = answer.toString();
            try {
                JSONObject jsonObject = new JSONObject(json);
                String key = "workAnswers";
                if (jsonObject.has(key)) {
                    JSONArray array = new JSONArray(answer.getWorkAnswers());
                    jsonObject.remove(key);
                    jsonObject.put(key, array);
                    json = jsonObject.toString();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            final String finalJson = json;
            EpaperDao.getInstance().submitReadWork(json, 0, answer.getWorkId(), answer.getContentId(), new BaseExtCallBack(RereadWordResultActivity.this, getUserInfoBase().getUserId() + "") {
                @Override
                public void success(Object data) {//try

                    SubmitResult submitResult = (SubmitResult) data;
                    doWorkId = submitResult.getDoWorkId();//返回DOWORKid
                    returnWorkLong = submitResult.getWorkLong();
                    Log.d(TAG, "#######提交作业 success#########");


                    commitSuccess();
                }

                @Override
                public void failed(final Object data) {

                    if (null != data) {
                        Log.d(TAG, "#######提交作业 failed#########" + data.toString());
                        FeedbackUtil.getInstance().addFeedbackLogWithJson(FeedbackUtil.FEEDBACK_TYPE_WORD_SPEECH, data.toString(), finalJson, "单词提交作业失败：" + getUrl());
                    }
                    try {
                        isHasSubmited = false;
                        netSpeedTask.cancel();//取消定时任务
                        result_contail.setVisibility(View.GONE);
                        submiting.setVisibility(View.GONE);
                        submit_fail.setVisibility(View.VISIBLE);
                    } catch (Exception e) {
                        e.getStackTrace();
                    }

                }

                @Override
                public void failed(final int errorCode, final Object data) {
                    try {
                        setUpload(false);
                        super.failed(errorCode, data);
                        if (errorCode == 105) {
                            commitSuccess();
                        } else {
                            if (null != data) {
                                Log.d(TAG, "#######提交作业 failederrorCode #########" + data.toString());
                                FeedbackUtil.getInstance().addFeedbackLogWithJson(FeedbackUtil.FEEDBACK_TYPE_WORD_SPEECH, data.toString(), finalJson, "单词提交作业失败：" + getUrl());

                            }

                            if (errorCode != EConstants.ERROR_CODE_REPEAT_COMMIT) {
                                isHasSubmited = false;
                                netSpeedTask.cancel();//取消定时任务
                                result_contail.setVisibility(View.GONE);
                                submiting.setVisibility(View.GONE);
                                submit_fail.setVisibility(View.VISIBLE);
                            } else {
                                commitSuccess();
                            }
                        }


                    } catch (Exception e) {
                        e.getStackTrace();
                    }

                }
            });

        } catch (Exception e) {
            e.getStackTrace();
        }

    }


    private void commitSuccess() {


        try {
            //清除做作业记录  相关缓存
            Intent intent = new Intent();
            intent.putExtra(IntentFlag.INTENT_FLAG_UUID, mUuid);
            intent.putExtra(IntentFlag.INTENT_FLAG_MP3_TYPE, IntentFlag.INTENT_FLAG_MP3_TYPE_WORD);
            intent.putExtra(IntentFlag.INTENT_FLAG_WORK_START_TIME, startTime);
            intent.setAction(IntentFlag.INTENT_FLAG_COMPLATE_ONE_HOMEWORK);
            sendBroadcast(intent);

            clearRecord();
            saveDoWorkRecord(null, null);

            //提交作业成功 清除开始时间
            CWSys.setSharedLong(ListenSpeakUtil.getAnswerStartTimeKey(mDownLoadInfo, mModule, position, workId), 0);
            UnitSpeechControler.readCount = 0;
            CWSys.setSharedInt(getSaveTime(), 0);
            result_contail.setVisibility(View.GONE);
            submiting.setVisibility(View.GONE);
            submit_fail.setVisibility(View.GONE);
            //结果页面
            submit_result_lay.setVisibility(View.VISIBLE);
            //
            updateUiSussess();//显示结果页面
            saveSubmitState(false);//提交过作业
            isSubmited = true;//提交成功
            isHasSubmited = false;
            sendBroadcast(new Intent(EpaperConstant.BROADCAST_HOME_WORK_STATUS_CHANGE_MSG));
            sendBroadcast(new Intent(EpaperConstant.BROADCAST_AUTONOMIC_STUDY_STATUS_CHANGE_MSG));
        } catch (Exception e) {
            e.getStackTrace();
        }


        try {

            //作业过来的
            if (Long.valueOf(workId) > 0 && mWorkContents != null) {
                score_result_page.setRankLinIsVis(View.VISIBLE);
                score_result_page.setOnToRankListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MeJumpManager.jumpToRankH5Activity(R.string.go_back, RereadWordResultActivity.this, mWorkContents.getContentId() + "", mWorkContents.getResourceName());
                    }
                });
            } else {
                //自主学习
                score_result_page.setRankLinIsVis(View.GONE);
            }

        } catch (Exception e) {
            score_result_page.setRankLinIsVis(View.GONE);
            e.printStackTrace();
        }

    }

    public void updateUiSussess() {//更新结果页UI
        score_result_page.setDispayType(SubmitSuccessfulResultPage.DISPLAY_TYPE_WORD);

        //先设置总分
        if (null != mWorkContents && mWorkContents.getWorkScore() > 0) {
            totalScore = mWorkContents.getWorkScore();
            nowTime = mWorkContents.getNowDate();
            // 查看类型：0 提交立马能查看，1截止时间到后查看
            showScoreMode = mWorkContents.getShowScoreMode();
        }
        score_result_page.setToalScore(totalScore);
        score_result_page.setScoreText(mAnswerRecorderList.size() + "");
        if (acuScore == -1) {
            acuScore = 0;
        }
        score_result_page.setEvaluateState(0, true, acuScore + "", -1, nowTime, effectiveDate, showScoreMode, serviceExpired);
        score_result_page.setTitleText(mTitleText);
        //如果返回作业用时失败 则使用旧用时
        if (returnWorkLong != 0) {
            score_result_page.setWorkTime(ListenSpeakUtil.formatWorkLong(this, (int) returnWorkLong));
        } else {
            score_result_page.setWorkTime(ListenSpeakUtil.formatWorkLong(this, workLong));
        }

        hideTitleBar();
        //从作业列表进来的
        if (Long.valueOf(workId) > 0 && mWorkContents != null) {
            RequirementContent requirementContent = new Gson().fromJson(mWorkContents.getRequirementContent(),
                    RequirementContent.class);
            int requireTimes = requirementContent.getReadtimes();
            int submitCounts = mWorkContents.getSubmitCount() + 1;
            if (submitCounts >= requireTimes) {
                score_result_page.tv_submit_description.setVisibility(View.INVISIBLE);
                btn_return_last_page.setText("完成");
            } else {
                score_result_page.tv_submit_description.setVisibility(View.VISIBLE);
                btn_return_last_page.setText("再次跟读");
                mWorkContents.setSubmitCount(mWorkContents.getSubmitCount() + 1);
            }
            score_result_page.tv_submit_description.setText(score_result_page.wordDyeing("老师要求读" + requireTimes + "次，", "已读" + submitCounts + "次"));
        } else {
            score_result_page.tv_submit_description.setVisibility(View.INVISIBLE);
            btn_return_last_page.setText("完成");
        }


    }

    /**
     * 获取平均分
     *
     * @return
     */
    public int getAvgScore() {
        int len = mAnswerRecorderList.size();
        int total = 0;

        for (AnswerRecorder ar : mAnswerRecorderList) {
            if (ar != null) {
                total += ar.getScore();
            }
        }
        BigDecimal bTotal = new BigDecimal(total);
        BigDecimal bLen = new BigDecimal(len);
        int avgIntScore = 0;
        if (bLen.intValue() > 0) {
            avgIntScore = bTotal.divide(bLen, 0, BigDecimal.ROUND_HALF_UP).intValue();
        }

        if (total > 0 && avgIntScore == 0) {
            // 算的平均分为0分有问题
            avgIntScore = (int) (total / len);
            return avgIntScore;
        } else {
            return avgIntScore;
        }
//        return new BigDecimal(avg).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
    }


    /**
     * 获取提交状态的key
     *
     * @return
     */
    protected String getSubmitStateKey() {
        String key = ESystem.getSaveRecordKeywithModeandUUid(mDownLoadInfo, mModule, position,
                workId,
                SerializableManager.SerializeKey.SUBMIT_STATE, readMode, mUuid);
        return key + "_" + getUserInfoBase().getUserId();
    }

    /**
     * 保存答案记录和UUID记录
     *
     * @param userAnswersList
     * @param answerRecorderList
     */
    protected void saveDoWorkRecord(ArrayList<WorkAnswers<RepeatAnswerInfo>> userAnswersList, ArrayList<AnswerRecorder> answerRecorderList) {
        String key = RepeatKeyUtil.getWordRepeatAnswerListKey(mDownLoadInfo, mModule, position, workId, mUuid);
        SerializableManager.getInstance().serialize(key, userAnswersList);
        String keyDoWork = RepeatKeyUtil.getWordRepeatRecordListKey(mDownLoadInfo, mModule, position, workId, mUuid);
        SerializableManager.getInstance().serialize(keyDoWork, answerRecorderList);
    }


    /**
     * 获取作业用时
     *
     * @return
     */
    protected String getSaveTime() {
        String key = ESystem.getSaveRecordKeywithMode(mDownLoadInfo, mModule, position,
                workId,
                SerializableManager.SerializeKey.SHARE_KEY_DO_WORK_TIME, readMode);
        return key + "_" + getUserInfoBase().getUserId();
    }


    /**
     * 保存答案记录和UUID记录
     *
     * @param
     */
    protected void saveSubmitState(
            boolean submit) {
        CWSys.setSharedBoolean(getSubmitStateKey(), submit);
    }

    @Override
    protected void onDestroy() {
        UnitSpeechControler.readCount = 0;
        super.onDestroy();
    }


    //检测网速任务
    TimerTask netSpeedTask = new TimerTask() {
        @Override
        public void run() {

            if (!isSubmited && !isFinishing()) {
                showNetSpeed();
            } else {
                //提交成功后就不需要展示网络状况
                cancel();
            }

        }
    };
    private long lastTotalRxBytes = 0;
    private long lastTimeStamp = 0;


    private void showNetSpeed() {

        long nowTotalRxBytes = getTotalRxBytes();
        long nowTimeStamp = System.currentTimeMillis();
        long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));//毫秒转换
        if (speed < 3) {
            Random rand = new Random();
            speed = rand.nextInt(3);
        }

        lastTimeStamp = nowTimeStamp;
        lastTotalRxBytes = nowTotalRxBytes;

        Message msg = mHandler.obtainMessage();
        msg.what = MSG_NET_SPEED;
//        Log.d(TAG, "################String.valueOf(speed)################"+String.valueOf(speed));
        msg.obj = (int) speed;
        mHandler.sendMessage(msg);//更新界面
    }

    private long getTotalRxBytes() {
        return TrafficStats.getUidRxBytes(getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ? 0 : (TrafficStats.getTotalRxBytes() / 1024);//转为KB
    }

    private long getRemainUploadFileSize() {
        long remainSize = 0;
        try {
            for (AnswerRecorder answerRecorder : mAnswerRecorderList) {
                if ("".equals(answerRecorder.getAliyunSoundUrl()) || null == answerRecorder.getAliyunSoundUrl()) {
                    if ((!"".equals(answerRecorder.getSoundUrl())) && (null != answerRecorder.getSoundUrl())) {
                        File file = new File(answerRecorder.getSoundUrl());
                        if (file.exists()) {
                            remainSize = remainSize + file.length();
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
        return remainSize / 1024;
    }

    /**
     * 退出提示框
     */
    private void showConfirmEndDialog() {
        if (isDestroy) {
            return;
        }
        CWDialog dialog = new CWDialog(this);
        dialog.setMessage(R.string.confirm_no_submit_work);
        dialog.setCancelable(true);
        dialog.setPositiveButton(android.R.string.cancel, null)
                .setNegativeButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();

                                finish();

                            }
                        })
                .show();
    }

    GoBackListener goBackListener = new GoBackListener() {
        @Override
        public void goBack() {
            if (isHasSubmited) {
                saveDoWorkRecord(userAnswersList, mAnswerRecorderList);
                showConfirmEndDialog();
            } else if (isSubmited) {
                saveDoWorkRecord(null, null);
                FileUtils.delete(ESystem.getAnswersUuidPath(mUuid));
                CWSys.setSharedInt(getSaveTime(), 0);
                sendBroadcast(new Intent(EpaperConstant.BROADCAST_HOME_WORK_STATUS_CHANGE_MSG));
                sendBroadcast(new Intent(EpaperConstant.BROADCAST_AUTONOMIC_STUDY_STATUS_CHANGE_MSG));
                finish();
            } else {
                showDailog();
                saveDoWorkRecord(userAnswersList, mAnswerRecorderList);

            }
            UnitSpeechControler.readCount = 0;
        }
    };


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_return_last_page) {
            if ("再次跟读".equals(btn_return_last_page.getText().toString())) {

                //作业才会有再次跟读情况
                EpaperJumpManager.jumpToWordRead(R.string.go_back,
                        this, workId, mDownLoadInfo, mModule, requirementContent, position, readMode,
                        RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_DO_WORK, answer.getClassId(), answer.getVersionId(), answer.getWorkType(), false, mWorkContents, effectiveDate);
                finish();

            } else {
                Intent intent = new Intent(EpaperConstant.INTENT_BOACK_REF_WORK);
                //        作业状态(1:已提交 2:退回 4:已批改完成 8:无法识别答题卡 16:等待批改)
                int workStatus = 1;//听说模考评分中传16，其他默认传1.
                intent.putExtra(IntentFlag.INTENT_FLAG_WORK_STATUS, workStatus);//
                intent.putExtra(IntentFlag.INTENT_FLAG_ACTUAL_SCORE, acuScore);
                sendBroadcast(intent);
                finish();
            }
        } else if (id == R.id.iv_close_page) {
            UnitSpeechControler.readCount = 0;
            Intent intent = new Intent(EpaperConstant.INTENT_BOACK_REF_WORK);
            //        作业状态(1:已提交 2:退回 4:已批改完成 8:无法识别答题卡 16:等待批改)
            int workStatus = 1;//听说模考评分中传16，其他默认传1.
            intent.putExtra(IntentFlag.INTENT_FLAG_WORK_STATUS, workStatus);//
            intent.putExtra(IntentFlag.INTENT_FLAG_ACTUAL_SCORE, acuScore);
            sendBroadcast(intent);
            finish();
        }
    }

    /**
     * 清除记录
     */
    private void clearRecord() {
//        清除本次做作业或自主练习活动key,只有活动key 清

        CWSys.setSharedString(RepeatKeyUtil.getWordUuidSaveKey(mDownLoadInfo, mModule, position, workId, readMode), null);
    }


    /**
     * 获取上传MP3 文件KEY
     *
     * @param uploadFilePath 上传文件路径
     * @return KEY
     */
    private String getMP3Key(String uploadFilePath) {
        return "work/followread/" + CWUtils.getReadTime(startTime) + "/" + CWSys
                .getSharedLong(BaseConstants.SHARE_PRE_CURR_LOGIN_USER, 0) + "/"
                + new File(uploadFilePath).getName();
    }


}
